<script setup>
import { onMounted, ref, watch } from 'vue'
import { queryPageApi, addEmpApi, queryEmpByIdApi, updateEmpApi, deleteEmpByidsApi } from '@/api/emp'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryAllApi } from '@/api/dept'
//定义表单搜索数据
const searchEmp = ref({
  name: '',
  gender: '',
  date: [],
  begin: '',
  end: ''
})
//重置搜索条件
const handleReset = () => {
  searchEmp.value.name = ''
  searchEmp.value.gender = ''
  searchEmp.value.date = []
  searchEmp.value.begin = ''
  searchEmp.value.end = ''
  getData()
}
//监听日期数据
watch(() => searchEmp.value.date, (newValue, oldValue) => {
  if (newValue.length === 2) {
    searchEmp.value.begin = newValue[0]
    searchEmp.value.end = newValue[1]
  } else {
    searchEmp.value.begin = ''
    searchEmp.value.end = ''
  }
})
//获取数据集合封装
const empList = ref([])
//分页数据处理
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const size = 'default'
const disabled = false
const background = true
//分页每页大小发生改变
const handleSizeChange = (val) => {
  // console.log(`${val} items per page`)
  //页码从第1页开始
  currentPage.value = 1
  // 每页多少条
  pageSize.value = val
  //搜索
  getData()
}
//分页页码发生改变
const handleCurrentChange = (val) => {
  // console.log(`current page: ${val}`)
  //前页发生变化
  currentPage.value = val
  getData()
}
// 获取数据搜索
const getData = async () => {
  //调用接口
  let result = await queryPageApi(searchEmp.value.name, searchEmp.value.gender, searchEmp.value.begin, searchEmp.value.end, currentPage.value, pageSize.value)
  //赋值给数据源集合
  empList.value = result.data.rows
  // 赋值给总页数
  total.value = result.data.total
}
// 控制对话框
const dialogShow = ref(false)
// 控制对话框标题显示
const Tips = ref('')
const showDialog = () => {
  dialogShow.value = true
  Tips.value = '新增员工'
  //清空表单数据
  formData.value = { image: '', username: '', name: '', gender: '', job: '', entryDate: '', deptId: '', phone: '', salary: '', exprList: [] }
  //判断表单是否已经挂载，没有挂载则跳过下面的操作
  if (!ruleFormRef.value) return
  //清除表单所有字段的内容，并清除校验错误提示
  ruleFormRef.resetFields()
}
// 弹框表单数据
const formData = ref({
  image: '',
  username: '',
  name: '',
  gender: '',
  job: '',
  entryDate: '',
  deptId: '',
  phone: '',
  salary: '',
  exprList: []
})
//头像设置
//上传成功后调用的方法
const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  formData.value.image = response.data
}
//上传前校验
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/png') {
    ElMessage.error('图片格式必须是 png 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不得超过 2MB!')
    return false
  }
  return true
}

//定义性别、职位、部门下拉数据
const genderList = ref([
  { id: 1, name: '男' },
  { id: 2, name: '女' }
])
const jobList = ref([
  { id: 1, name: '班主任' },
  { id: 2, name: '讲师' },
  { id: 3, name: '学工主管' },
  { id: 4, name: '教研主管' },
  { id: 5, name: '咨询师' },
  { id: 6, name: '其他' }
])
const deptList = ref([])
//获取所有部门
const queryAllDept = async () => {
  let res = await queryAllApi()
  deptList.value = res.data
}
//新增工作经历
const addWork = () => {
  formData.value.exprList.push({
    company: '',
    job: '',
    start: '',
    end: ''
  })
}
//深度侦听date
//watch(formData, (newValue, oldValue) => {
//  formData.value.exprList.forEach((item, index) => {
//    if (item.date) {
//      formData.value.exprList[index].begin = item.date[0]
//      formData.value.exprList[index].end = item.date[1]
//    }
//  })
//}, { deep: true })
//侦听exprList集合变化
watch(
  () => formData.value.exprList.map(item => item.date),
  (newDates) => {
    newDates.forEach((date, index) => {
      if (date && date.length === 2) {
        formData.value.exprList[index].begin = date[0]
        formData.value.exprList[index].end = date[1]
      }
    })
  }
)
//删除工作经历
const deleteWork = (index) => {
  formData.value.exprList.splice(index, 1)
}
//弹窗表单校验
const ruleFormRef = ref(null)
//表单校验规则
// 验证规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/g, message: '请输入有效的手机号', trigger: 'blur' }
  ]
})
//点击保存进行表单校验
const add = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid, fields) => {
    let result = null
    if (valid) {
      if (formData.value.id) {
        result = await updateEmpApi(formData.value)
        if (result.code) {
          ElMessage.success('修改员工成功！')
          dialogShow.value = false
          getData()
        } else {
          ElMessage.error('修改员工失败！')
        }
      } else {
        result = await addEmpApi(formData.value)
        if (result.code) {
          ElMessage.success('员工添加成功')
          dialogShow.value = false
          getData()
        } else {
          ElMessage.error('员工添加失败')
        }
      }
      // console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
//根据Id查询回显
const handleEdit = async (id) => {
  let result = await queryEmpByIdApi(id)
  formData.value = result.data
  //日期进行转换
  formData.value.exprList.forEach(item => {
    item.date = []
    item.date.push(item.begin)
    item.date.push(item.end)
  })
  dialogShow.value = true
  Tips.value = '修改员工信息'
  // queryAllDept()
}
//批量删除员工
//定义集合存储删除的id集合
const ids = ref([])
const name = ref([])
//将所有的选中的id存入到ids集合中
const handleSelectionChange = (selection) => {
  let result = selection.map(item => item.id)
  ids.value = result
  let empName = selection.map(item => item.name)
  name.value = empName
  // console.log(result)
}
const deleteEmpByids = async () => {
  ElMessageBox.confirm('确定要删除姓名为: ' + name.value + '的员工吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let result = await deleteEmpByidsApi(ids.value)
    if (result.code) {
      ElMessage.success('删除成功！')
      getData()
    } else {
      ElMessage.success('删除失败！')
      getData()
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}
//单个删除员工
const handleDelete = async (row) => {
  ids.value = row.id
  name.value = row.name
  await deleteEmpByids()
}
//图片上传401解决
//定义存储token
const token = ref({ token: '' })
//方法获取token
const getToken = () => {
  let userInfo = localStorage.getItem('loginUser')
  if (userInfo) {
    token.value.token = JSON.parse(userInfo).token
  }
  // token.value.token=JSON.parse(localStorage.getItem('loginUser')).token
}
//预加载
onMounted(() => {
  getData()
  queryAllDept()
  getToken()
})
</script>

<template>
  <h1>员工管理</h1> <br>
  <!-- 搜索框 -->
  <el-form :inline="true" :model="searchEmp">
    <el-form-item label="姓名">
      <el-input v-model="searchEmp.name" placeholder="请输入员工姓名"></el-input>
    </el-form-item>

    <el-form-item label="性别">
      <el-select v-model="searchEmp.gender" placeholder="请选择">
        <el-option label="男" value="1"></el-option>
        <el-option label="女" value="2"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="入职日期">
      <el-date-picker v-model="searchEmp.date" type="daterange" range-separator="至" start-placeholder="开始日期"
        end-placeholder="结束日期" value-format="YYYY-MM-DD"></el-date-picker>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="getData()">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>
  <el-button type="primary" @click="showDialog"> + 新增员工</el-button>
  <el-button type="danger" @click="deleteEmpByids"> - 批量删除</el-button>
  <!-- 弹窗（新增/修改） -->
  <el-dialog v-model="dialogShow" :title="Tips" width="800px">
    <!-- 表单显示 -->
    <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="auto" style="max-width: 800px">
      <!-- 第一行 -->
      <el-row :gutter="6">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username" style="width: 100%;">
            <el-input v-model="formData.username" placeholder="请输入员工用户名" clearable style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name" style="width: 100%;">
            <el-input v-model="formData.name" placeholder="请输入员工姓名" clearable style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第二行 -->
      <el-row :gutter="6">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender" style="width: 100%;">
            <el-select v-model="formData.gender" placeholder="请选择性别" style="width: 100%;" clearable>
              <el-option v-for="(gender, index) in genderList" :key="index" :label="gender.name" :value="gender.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone" style="width: 100%;">
            <el-input v-model="formData.phone" placeholder="请输入员工手机号" style="width: 100%;" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第三行 -->
      <el-row :gutter="6">
        <el-col :span="12">
          <el-form-item label="职位" style="width: 100%;">
            <el-select v-model="formData.job" placeholder="请选择职位" style="width: 100%;" clearable>
              <el-option v-for="(job, index) in jobList" :key="index" :label="job.name" :value="job.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资" style="width: 100%;">
            <el-input v-model="formData.salary" placeholder="请输入员工薪水" style="width: 100%;" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第四行 -->
      <el-row :gutter="6">
        <el-col :span="12">
          <el-form-item label="部门" style="width: 100%;">
            <el-select v-model="formData.deptId" placeholder="请选择部门" style="width: 100%;" clearable>
              <el-option v-for="(dept, index) in deptList" :key="index" :label="dept.name" :value="dept.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期" style="width: 100%;">
            <el-date-picker v-model="formData.entryDate" type="date" placeholder="选择日期" style="width: 100%;"
              clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第五行 -->
      <!-- 头像 -->
      <el-row :gutter="6">
        <el-col :span="24">
          <el-form-item label="头像" style="width: 100%;">
            <el-upload class="avatar-uploader" action="/api/upload" :headers="token" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="formData.image" :src="formData.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第六行 -->
      <!-- 工作经历按钮 -->
      <el-row :gutter="6">
        <el-col :span="24">
          <el-form-item label="工作经历" label-width="80px">
            <el-button type="success" @click="addWork()"> + 添加工作经历</el-button>
            <!-- {{ formData.exprList }} -->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="(exp, index) in formData.exprList" :key="index" :gutter="3">
        <el-col :span="10">
          <el-form-item size="small" label="时间" label-width="80px">
            <el-date-picker v-model="exp.date" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item size="small" label="公司" label-width="60px">
            <el-input v-model="exp.company" placeholder="请输入公司名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item size="small" label="职位" label-width="60px">
            <el-input v-model="exp.job" placeholder="请输入职位"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item size="small" label-width="0px">
            <el-button type="danger" @click="deleteWork(index)">- 删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogShow = false">取消</el-button>
        <el-button type="primary" @click="add()"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
  <br><br>
  <!-- 表格展示 -->
  <div>
    <el-table :data="empList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column fixed="left" :selectable="selectable" type="selection" width="55" align="center" />
      <el-table-column type="index" prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="name" label="姓名" width="180" align="center" />
      <el-table-column prop="gender" label="性别" width="180" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.gender === 1">男</el-tag>
          <el-tag v-else>女</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="image" label="头像" width="180" align="center">
        <template #default="scope">
          <img :src="scope.row.image" style="width: 50px;height: 50px;">
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="部门名称" width="180" align="center" />
      <el-table-column prop="job" label="职位" width="180" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.job === 1">班主任</el-tag>
          <el-tag v-else-if="scope.row.job === 2">讲师</el-tag>
          <el-tag v-else-if="scope.row.job === 3">学工主管</el-tag>
          <el-tag v-else-if="scope.row.job === 4">教研主管</el-tag>
          <el-tag v-else-if="scope.row.job === 5">咨询师</el-tag>
          <el-tag v-else>其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="entryDate" label="入职日期" width="180" align="center" />
      <el-table-column prop="updateTime" label="最后操作时间" width="180" align="center" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleEdit(scope.row.id)">编辑</el-button>
          <el-button link type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <br />
  <!-- 分页 -->
  <div>
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20, 25, 30]"
      :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

</template>

<style scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>